#!/bin/sh
#
# Webif post-install script.
#

webif_installed_mark="/tmp/.webif-installed-marker"

#########################################################################################
# functions

TestInstall()
{
	this_version="__SVN_REVISION__"
	installed_version=$(cat "${IPKG_INSTROOT}/www/.version")
	if [ -f "/www/.version" ] && [ "$this_version" = "$installed_version" ]; then
		echo "SUCCESS! Webif^2 installation appears OK. Welcome to X-Wrt!"
		echo "You may need to do a hard REFRESH to clear old CSS style from your browser."
	else
		echo "WARNING: Installation may have failed."
		echo " Detected r$installed_version is installed, but this is r$this_version."
	fi
}

ExecuteIfExists()
{
	# $1 = exec name
	# $2-$9 = params
	[ -f "$1" ] && {
		"$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
	}
}

# for squashfs symlink hacks like in WR RC5 (requires rm before change)
FixReadOnlyLink()
{
	touch "$1" >&- 2>&-	# test if read-only
	[ "$?" != 0 ] && {
		local tmpfile=$(mktemp "${IPKG_INSTROOT}/tmp/.webif-inst-XXXXXX")
		cp -p "$1" "$tmpfile" >&- 2>&-
		rm "$1"  >&- 2>&-
		mv "$tmpfile" "$1"  >&- 2>&-
	}
}

IPKG_UPDATE_NEEDED="0"
AddRepository()
{
	# $1=reponame
	# $2=repourl
	# $3=force last
	cat "${IPKG_INSTROOT}/etc/ipkg.conf" | grep -q "^src .*$2"
	[ "$?" != "0" ] && IPKG_UPDATE_NEEDED="1" || {
		[ "$(grep "^src .*$2" "${IPKG_INSTROOT}/etc/ipkg.conf" | cut -d' ' -f2)" != "$1" ] && {
			DeleteRepository "$2" 1
			IPKG_UPDATE_NEEDED="1"
		} || {
			DeleteRepository "$2"
		}
	}
	local ltmp=$(mktemp "/tmp/.webif-XXXXXX")
	cp -p "${IPKG_INSTROOT}/etc/ipkg.conf" "$ltmp" >&- 2>&-
	echo -n "" > "$ltmp" >&- 2>&-
	[ "$3" != "1" ] && echo "src $1 $2" > "$ltmp"
	grep "^src " "${IPKG_INSTROOT}/etc/ipkg.conf" >> "$ltmp"
	[ "$3" = "1" ] && echo "src $1 $2" >> "$ltmp"
	grep -v "^src " "${IPKG_INSTROOT}/etc/ipkg.conf" >> "$ltmp"
	rm -f "${IPKG_INSTROOT}/etc/ipkg.conf" >&- 2>&-
	mv -f "$ltmp" "${IPKG_INSTROOT}/etc/ipkg.conf"
}

IPKG_UPDATE_NEEDED="0"
DeleteRepository()
{
	# $1=repourl
	# $2=force removal of the ipkg list
	cat "${IPKG_INSTROOT}/etc/ipkg.conf" | grep -q "^src .*$1"
	[ "$?" = "0" ] && {
		[ "$2" = "1" ] && {
			local list=$(grep "^src .*$1" "${IPKG_INSTROOT}/etc/ipkg.conf" | cut -d' ' -f2)
			rm -f "${IPKG_INSTROOT}/usr/lib/ipkg/lists/$list" 2>/dev/null
		}
		local repo_url_sed=$(echo "$1" | sed s/'\/'/'\\\/'/g)
		cat "${IPKG_INSTROOT}/etc/ipkg.conf" |  sed /$repo_url_sed/d > "${IPKG_INSTROOT}/etc/ipkg.conf"
	}
}

is_package_installed() {
	# $1 = package name
	# returns 0 if package is installed.
	for LOCATION in $(grep "^dest\>" /etc/ipkg.conf | cut -d ' ' -f 3); do

		if [ "$LOCATION" = "/" ]; then
		        paths="$paths /usr/lib/ipkg/status"
		else
		        paths="$paths $LOCATION/usr/lib/ipkg/status"
		fi
	done
	grep -q " $1\$" $paths >> /dev/null 2>&1
}


#########################################################################################
# entry point

# fix some links on squashfs partition that aren't properly copied instead by firstboot
# has no effect when done in image builder.
FixReadOnlyLink "${IPKG_INSTROOT}/usr/lib/ipkg/info/webif.list"
FixReadOnlyLink "${IPKG_INSTROOT}/etc/ipkg.conf"
FixReadOnlyLink "${IPKG_INSTROOT}/usr/lib/ipkg/status"

# copy our new httpd.conf and S50dnsmasq files - we renamed them so that the webif can
# be uninstalled without ipkg removing these pre-existing files as well.
dnsmasq_filename="S50dnsmasq"
[ -f "${IPKG_INSTROOT}/etc/init.d/S60dnsmasq" ] && {
	# S50dnsmasq renamed to S60dnsmasq in post-RC6
	dnsmasq_filename="S60dnsmasq"
}
rm -f "${IPKG_INSTROOT}/etc/init.d/S?0dnsmasq"
rm -f "${IPKG_INSTROOT}/etc/httpd.conf"
mv -f "${IPKG_INSTROOT}/etc/init.d/x50dnsmasq.webif" "${IPKG_INSTROOT}/etc/init.d/${dnsmasq_filename}"
rm -f "${IPKG_INSTROOT}/etc/init.d/S60cron"
mv -f "${IPKG_INSTROOT}/etc/init.d/x60cron.webif" "${IPKG_INSTROOT}/etc/init.d/S60cron"
mv -f "${IPKG_INSTROOT}/etc/httpd.webif" "${IPKG_INSTROOT}/etc/httpd.conf"

# initialize default webif theme
# create symlink to /www/themes/xwrt (do NOT use INSTROOT in first arg).
rm -rf "${IPKG_INSTROOT}/www/themes/active" >&- 2>&-
ln -sf "/www/themes/xwrt" "${IPKG_INSTROOT}/www/themes/active" >&- 2>&-
[ $? != 0 ] && {
	# if fs doesn't support symlinks, do a copy
	mkdir -p "${IPKG_INSTROOT}/www/themes/active"
	cp -p "/www/themes/xwrt/*" "/www/themes/active/"
}

# initialize webifmetabin binaries
# todo: move back to makefile because this won't be cleaned up good
# for RC5, do an rm first
rm -f "${IPKG_INSTROOT}/usr/bin/bstrip"
rm -f "${IPKG_INSTROOT}/usr/bin/webif-page"
rm -f "${IPKG_INSTROOT}/usr/bin/wepkeygen"
rm -f "${IPKG_INSTROOT}/usr/bin/int2human"
# -f is not needed, but we'll keep in case above is removed
ln -sf /usr/bin/webifmetabin "${IPKG_INSTROOT}/usr/bin/bstrip"
ln -sf /usr/bin/webifmetabin "${IPKG_INSTROOT}/usr/bin/webif-page"
ln -sf /usr/bin/webifmetabin "${IPKG_INSTROOT}/usr/bin/wepkeygen"
ln -sf /usr/bin/webifmetabin "${IPKG_INSTROOT}/usr/bin/int2human"

# initialize ipkg.conf
[ -z "$IPKG_INSTROOT" ] && firmware_version=$(nvram get firmware_version)
if [ "$firmware_version" = "RC5" ] || grep -q "RC5" "${IPKG_INSTROOT}/etc/banner"; then
	DeleteRepository "http://downloads.openwrt.org/backports/rc4" 1
	AddRepository "rc5-backports" "http://downloads.openwrt.org/backports/rc5"
elif [ "$firmware_version" = "RC6" ] || grep -q "RC6" "${IPKG_INSTROOT}/etc/banner"; then	
	DeleteRepository "http://downloads.openwrt.org/backports/rc5" 1
	AddRepository "rc6-backports" "http://downloads.openwrt.org/backports/rc6"	
elif [ "$firmware_version" = "0.9" ] || grep -q "0.9" "${IPKG_INSTROOT}/etc/banner"; then	
	# delete all previous backports, all lost packages are in our repository
	DeleteRepository "http://downloads.openwrt.org/backports/rc4" 1
	DeleteRepository "http://downloads.openwrt.org/backports/rc5" 1
	DeleteRepository "http://downloads.openwrt.org/backports/rc6" 1
	AddRepository "0.9-backports" "http://downloads.openwrt.org/backports/0.9"
else
	echo "White Russian version not detected. Not installing backports repository source."
fi
# add our repository and force it to be the last and the preferred one
AddRepository "X-Wrt" "http://download2.berlios.de/pub/xwrt/packages" 1

# only run below on 'real' system (not image builder)
if [ -z "${IPKG_INSTROOT}" ]; then	
	[ "$IPKG_UPDATE_NEEDED" = "1" ] && ipkg update

	# force the reinstallation of uci files when broken
	[ ! -f /lib/config/uci.sh ] && ipkg install base-files-uci -force-reinstall -force-overwrite

	# force re-initialization of extension package lists
	/usr/lib/webif/webif-mklanglist.sh
	/usr/lib/webif/webif-mkthemelist.sh
	
	is_package_installed webif-hotspot
	if [ "$?" = "0" ]; then
		cat "${IPKG_INSTROOT}/www/cgi-bin/webif/.categories" |sed '/##WEBIF:category:Network/a\
##WEBIF:category:Hotspot'>"${IPKG_INSTROOT}/www/cgi-bin/webif/.categories"
	fi
	
	is_package_installed webif-freeloader
	if [ "$?" = "0" ]; then
		cat "${IPKG_INSTROOT}/www/cgi-bin/webif/.categories" |sed '/##WEBIF:category:Network/a\
##WEBIF:category:Freeloader'>"${IPKG_INSTROOT}/www/cgi-bin/webif/.categories"
	fi
	
	# initialize config
	ExecuteIfExists "/etc/init.d/S90webif"

	# test installation successfulness
	TestInstall

	httpd_1=$(cat /tmp/httpd.conf.old)
	httpd_2=$(cat /etc/httpd.conf)
	rm -f /tmp/httpd.conf.old
	[ "$httpd_1" != "$httpd_2" ] && {
		echo "Reinitializing httpd ..."		
		killall -HUP httpd
	}
	[ ! -f "$webif_installed_mark" ] && {
		# webif^2 first install.. force reboot. Required, we've been through this.
		rm -f "$webif_installed_mark"
		echo "I'm sorry, but I must reboot your router. This is a ONE time thing and"
		echo " future upgrades of the webif will NOT require a reboot."
		echo "Please wait about one minute for your router to reboot ..."
		reboot_file=$(mktemp /tmp/rebootme.XXXXXX)
		echo "#!/bin/sh" > $reboot_file
		echo "sleep 5 && reboot" >> "$reboot_file"
		chmod +x "$reboot_file"
		sh "$reboot_file" &	
	}
fi
exit 0
